﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
//svnkit imports
using org.tmatesoft.svn.core;
using org.tmatesoft.svn.core.wc;

namespace Subsync.Core.Subversion
{
    class SVNUnlock : CommandBase
    {
        // Initialise variables with default settings.
        int no_of_filepath;
        public java.io.File[] file_path; //url of file to be locked
        bool breakLock = true; //other users may take over the lock

        // Minimal constructor.
        public SVNUnlock(string filePath)
        {
            Debug.WriteLine("SVN Unlock minimal Constructor with defaults");
            List<string> path = new List<string>();
            path.Add(filePath);
            this.setupUnlock(path, true);
        }

        // Full constructor
        public SVNUnlock(List<string> path, bool breakLock)
        {
            Debug.WriteLine("SVN Unlock full Constructor with defaults");

            setupUnlock(path, breakLock);
        }

        public void setupUnlock(List<string> path, bool brkLk)
        {
            this.breakLock = brkLk;
            int listSize = path.Count;
            this.file_path = new java.io.File[listSize];
            for (int i = 0; i < listSize; i++)
                file_path[i] = new java.io.File(path[i]);
        }

        public override void Execute()
        {
            Debug.WriteLine("SVN Unlock Execution");

            //library setup
            Tools.setupLibrary();

            //load up the clients
            SVNClientManager cm = SVNClientManager.newInstance();

            try
            {
                cm.getWCClient().doUnlock(this.file_path, this.breakLock);
            }
            catch (SVNException e)
            {
                throw new SVNExecuteException(e.getMessage());
            }
        }

        public override Dictionary<string, List<object>> getTokens ()
		{
			Dictionary<string, List<object>> ret = new Dictionary<string, List<object>> ();
			ret.Add("Unlock",new List<object>() {"ul","unlock"});
			return ret;
		}
		
		public override List<KeyValuePair<string,initPointer>> getInitPointers() {
			List<KeyValuePair<string,initPointer>> ret = new List<KeyValuePair<string,initPointer>>();
			ret.Add(new KeyValuePair<string,initPointer>("Unlock",new initPointer(this.handleCLI)));
			return ret;
		}
		
		public void handleCLI(Dictionary<string,List<object>> tokens) {
            no_of_filepath = tokens["Unlock"].Count;
			if (no_of_filepath == 0) {
				Console.WriteLine("Not enough arguments: Lock requires at least 1 argument - path");
				return;
			}
            List<string> path = new List<string>();
            for (int i = 0; i < no_of_filepath; i++)
                path.Add((string)tokens["Unlock"][i]);
			this.setupUnlock(path, true);
            this.Execute();
        }

        public SVNUnlock() {}
    }
}
